package com.fy.common.upload;

import cn.hutool.json.JSONUtil;
import com.fy.common.vo.ApiRest;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@CrossOrigin
@Api(description = "文件上传接口")
public class uploadController {
    @Value("${qiniu.ak}")
    String accessKey ;
    @Value("${qiniu.sk}")
    String secretKey ;
    @Value("${qiniu.bucket}")
    String bucket ;
    @Value("${qiniu.host}")
    String host;


    @PostMapping("upload")
    @ApiOperation("文件上传的业务接口")
    public ApiRest<String> upload(MultipartFile head) throws Exception{
        String originalFilename = head.getOriginalFilename();
        System.out.println("originalFilename = " + originalFilename);

        //file storage?   文件服务器(fastdfs)  （oss对象存储服务）云服务器【阿里云、腾讯云、华为云、七牛云】
        byte[] bytes = head.getBytes();
//-----------------------------------------------------------------------------------//
        // Region必须指定为bucket设置的地址
        Configuration cfg = new Configuration(Region.huanan());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        UploadManager uploadManager = new UploadManager(cfg);


        String key = null;
        //获取令牌
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        Response response = uploadManager.put(bytes, key, upToken);
        //解析上传成功的结果
        DefaultPutRet putRet = JSONUtil.toBean(response.bodyString(), DefaultPutRet.class);



        return ApiRest.success(host+putRet.key);
    }
}
